package cn.sylinx.horm.core;

import java.util.HashMap;
import java.util.Map;

import cn.sylinx.horm.config.OrmConfigHolder;
import cn.sylinx.horm.config.specific.SpecificConfigHolder;
import cn.sylinx.horm.core.interceptor.SqlClientProxy;
import cn.sylinx.horm.exception.HORMException;
import cn.sylinx.horm.util.GLog;
import cn.sylinx.horm.util.StrKit;

/**
 * 保存不同数据源客户端操作
 * 
 * @author johnhan
 *
 */
public enum DynamicClient {
    ;

    public static final String DEFAULT_DS_NAME = "_DEFAULT_DS_NAME_FOR_HORM_";
    private static final Map<String, SqlClient> clientMaps = new HashMap<>();

    // 获取默认SqlClient
    public static SqlClient get() {
        return get(DEFAULT_DS_NAME);
    }

    public static SqlClient get(String dsName) {

        if (StrKit.isBlank(dsName)) {
            dsName = DEFAULT_DS_NAME;
        }

        SqlClient sqlClient = clientMaps.get(dsName);
        if (sqlClient == null) {
            throw new HORMException("SqlClient NOT FOUND by name:" + dsName);
        }
        return sqlClient;
    }

    public static void register(SqlClient sqlClient) {
        GLog.info("Cached SqlClient:{}", sqlClient.getDataSourceName());
        // 注册SqlClientProxy
        clientMaps.put(sqlClient.getDataSourceName(), maybeProxyed(sqlClient));
    }

    private static SqlClient maybeProxyed(SqlClient sqlClient) {
        return OrmConfigHolder.hasSqlClientInterceptor()
                ? (SpecificConfigHolder.isSqlClientInterceptorEnable(sqlClient.getDataSourceName())
                        ? SqlClientProxy.create(sqlClient)
                        : sqlClient)
                : sqlClient;
    }
}